package com.example.onlinemarket.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.onlinemarket.Application;
import com.example.onlinemarket.R;
import com.example.onlinemarket.util.ActivityUtil;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.example.onlinemarket.Application.dismissProgressDialog;
import static com.example.onlinemarket.Application.loginUser;
import static com.example.onlinemarket.util.ActivityUtil.showBigImage;
import static com.example.onlinemarket.util.FileUtil.externalFilesDir;
import static com.example.onlinemarket.util.FileUtil.writeStream2File;
import static com.example.onlinemarket.util.HttpUtil.uploadUserImg;

public class ImgUpdateActivity extends BaseActivity {

    private CircleImageView userImg;
    private Button cameraBtn;
    private Button albumBtn;
    public static boolean isImgUpdated;

    //获取权限请求码
    private final int CAMERA_PERMISSION_REQUEST = 0;

    //Intent请求码
    private final int TAKE_PHOTO_REQUEST_CODE = 1;
    private final int GET_ALBUM_PHOTO_REQUEST_CODE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载资源
        loadResources();
    }

    private void loadResources() {
        //获取布局
        setContentView(R.layout.activity_img_update);
        //初始化组件
        initWidgets();
        //为组件设置事件监听器
        setWidgetsListener();
        //关闭加载提示框
        dismissProgressDialog();
    }

    private void setWidgetsListener() {
        cameraBtn.setOnClickListener(v -> {
            takePhoto();//调用相机拍照获取图片
        });
        albumBtn.setOnClickListener(v -> {
            openAlbum();//调用相册选择图片
        });
        userImg.setOnClickListener(v -> showBigImage(loginUser.getLocalPath()));
    }

    private void initWidgets() {
        isImgUpdated = false;
        userImg = findViewById(R.id.iv_img_img);
        cameraBtn = findViewById(R.id.btn_img_camera);
        albumBtn = findViewById(R.id.btn_img_album);
        Glide.with(this)
                .load(loginUser.getLocalPath())
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .override(450, 450).placeholder(R.drawable.ic_no_img).into(userImg);
    }

    //调用相册选择图片
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, GET_ALBUM_PHOTO_REQUEST_CODE);//启动相册
    }

    //调用相册获取图片
    private void getPhotoFromAlbum(Uri uri){
        new Thread(() -> {
            InputStream in = null;
            try {
                in = new BufferedInputStream(getContentResolver().openInputStream(uri));//根据URI直接获取输入流
                //为输入流创建标记，以便重复使用
                in.mark(in.available()+1);
                String fileName = externalFilesDir+loginUser.getImgPath();
                //将输入流输出为文件保存
                writeStream2File(fileName, in);
                //重置输入流
                in.reset();
                uploadUserImg(loginUser.getUserName(), loginUser.getImgPath());//向服务器上传新的用户头像
                Bitmap bitmap = BitmapFactory.decodeStream(in);//通过输入流，调用BitmapFactory.decodeStream()方法获取Bitmap对象
                isImgUpdated = true;
                runOnUiThread(() -> {//在主线程上更新UI
                    Glide.with(this)
                            .load(bitmap)
                            .skipMemoryCache(true)
                            .diskCacheStrategy(DiskCacheStrategy.NONE)
                            .override(450, 450).placeholder(R.drawable.ic_no_img).into(userImg);
                });
            } catch (Exception e) { e.printStackTrace(); }
            finally {
                if(in!=null)//关闭输入流
                    try { in.close(); } catch (IOException e) { e.printStackTrace(); }
            }
        }).start();
    }

    //调用相机拍照获取图片
    private void takePhoto() {
        //检查是否获取了相机权限
        if(!Application.checkPermission(ImgUpdateActivity.this, Manifest.permission.CAMERA))
            Application.requestPermissions(ImgUpdateActivity.this,
                    new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST);
        else
            //调用相机拍照获取图片
            getPhotoFromCamera();
    }

    //调用相机拍照获取图片
    private void getPhotoFromCamera() {
        new Thread(() -> {
            File outputImg = new File(externalFilesDir+loginUser.getImgPath());
            if(outputImg.exists()) outputImg.delete();//若已存在同名文件则删除
            try {
                outputImg.createNewFile();//创建新文件
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 仅当设置了MediaStore.EXTRA_OUTPUT参数时,系统将不再返回缩略图,而是会被完整保存以下路径
                Uri imgUri = FileProvider.getUriForFile(
                        ImgUpdateActivity.this, getPackageName(), outputImg);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
                runOnUiThread(() -> startActivityForResult(cameraIntent, TAKE_PHOTO_REQUEST_CODE));
            } catch (IOException e) { e.printStackTrace(); }
        }).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        if(resultCode==RESULT_OK){
            if(requestCode==TAKE_PHOTO_REQUEST_CODE){
                if(data!=null){
                    uploadUserImg(loginUser.getUserName(), loginUser.getImgPath());
                    Glide.with(this)
                            .load(loginUser.getLocalPath())
                            .skipMemoryCache(true)
                            .diskCacheStrategy(DiskCacheStrategy.NONE)
                            .override(450, 450).placeholder(R.drawable.ic_no_img).into(userImg);
                    isImgUpdated = true;
                }
            }
            if(requestCode==GET_ALBUM_PHOTO_REQUEST_CODE)
                getPhotoFromAlbum(data.getData());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==CAMERA_PERMISSION_REQUEST)
            if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED)
                getPhotoFromCamera();
    }
}